/*export default {}
addEventListener('message', e => {
  const { data } = e
  console.log(data)
  setTimeout(() => {
    return postMessage('线程完成')
  }, 1000)
})*/


// worker.js
self.onmessage = function(event) {
  if (event.data.type === 'START') {
    const { ruleForm, thread } = event.data.data;
    const parsedRuleForm = JSON.parse(ruleForm);

    let count = 0;
    const interval = setInterval(() => {
      for (let i = 0; i < thread; i++) {
        const wallet = generateWallet(parsedRuleForm);
        if (wallet) {
          self.postMessage({
            address: wallet.address,
            privateKey: wallet.privateKey
          });
          clearInterval(interval);
          return;
        }
        count++;
      }
    }, 100);
  }
};

function generateWallet(ruleForm) {
  const { ethers } = require('ethers');
  const wallet = ethers.Wallet.createRandom();
  let address = wallet.address;
  if (!ruleForm.caseSensitive) {
    address = address.toLowerCase();
  }

  const prefix = ruleForm.caseSensitive ? ruleForm.before : ruleForm.before.toLowerCase();
  const suffix = ruleForm.caseSensitive ? ruleForm.after : ruleForm.after.toLowerCase();

  if ((!prefix || address.slice(2).startsWith(prefix)) &&
      (!suffix || address.endsWith(suffix))) {
    return wallet;
  }
  return null;
}
